package com.sx.zongzhi.widget;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sx.zongzhi.R;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.voiceamr.MediaReocderOpt;
import com.sx.zongzhi.voiceamr.Player;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by HuGe
 *
 * on 2017/6/30.
 * 自定义dialog 与AlertDialog 一样
 */
public class AudioDialog extends Dialog implements View.OnClickListener{

    private Context context;
    private ImageView ivToggle;
    private ImageView iv_close;
    private TextView numTime;
    // 获取类的实例
    private MediaReocderOpt recorder;
    //录音地址
    private String filePath;
    private int maxTime = 20;//20秒
    private int countdown = 0;//倒计时
    private boolean isStart = false;
    private AudioCallback mCallback;
    private Player player;
    public int AUDIO_PLAY=1;
    public int AUDIO_RECODERD=2;

    public AudioDialog(Context context) {
        super(context, R.style.Dialog);
        this.context=context;
        // 拿到Dialog的Window, 修改Window的属性
        Window window = getWindow();
        if (window!=null) {
            window.getDecorView().setPadding(0, 0, 0, 0);
            // 获取Window的LayoutParams
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.width = ViewGroup.LayoutParams.MATCH_PARENT;
            attributes.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
            window.setAttributes(attributes);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audio_dialog);
        initView();
    }

    private void initView() {
        ivToggle= (ImageView) findViewById(R.id.iv_toggle);
        iv_close= (ImageView) findViewById(R.id.iv_close);
        numTime= (TextView) findViewById(R.id.numTime);
        File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Voice");
        if (!file1.exists()){
            file1.mkdirs();
        }
        recorder = new MediaReocderOpt();
        ivToggle.setOnClickListener(this);
        iv_close.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.iv_toggle){
            if (isStart){
                isStart = false;
                if (ivToggle != null){
                    ivToggle.setImageResource(R.mipmap.icon_stop);
                }
                stopRecord();
                if (!new File(filePath).exists()) {
                    Toast.makeText(context, "录音失败", Toast.LENGTH_SHORT).show();
                } else {
                    if (mCallback!=null){
                        mCallback.getData(filePath,countdown);
                    }
                }
            }else {
                isStart = true;
                if (ivToggle != null){
                    ivToggle.setImageResource(R.mipmap.icon_recording);
                }
                startRecord();
            }
        }
        if (v.getId()==R.id.iv_close){
            dismiss();
        }
    }

    /**
     * 开始播放
     * @param path
     */
    public void startPlay(String path){
        show(AUDIO_PLAY);
        if (player == null){
            player = new Player(context);
        }
        if (player.isPlay()){
            player.stop();
        }
        player.playUrl(path, numTime, new Player.OnCompletionListener() {
            @Override
            public void onPlayComplet() {
               dismiss();
            }
        });
    }


    public void show(int TYPE) {
        super.show();
        if (AUDIO_PLAY==TYPE){
            ivToggle.setEnabled(false);
            Glide.with(context).load(R.mipmap.icon_play_audio).into(ivToggle);
            iv_close.setVisibility(View.VISIBLE);
        }
        if (AUDIO_RECODERD==TYPE){
            if (recorder!=null) {
                String name = BaseUtil.getTime();
                filePath = Environment.getExternalStorageDirectory().getAbsolutePath() +
                        File.separator + "Voice"+ File.separator+name +"media.amr";
                recorder.Init(filePath);
            }
            ivToggle.setEnabled(true);
            ivToggle.setImageResource(R.mipmap.icon_stop);
            iv_close.setVisibility(View.GONE);
        }
    }

    public void dismiss() {
        super.dismiss();
            if (player!=null&&player.isPlay()){
                player.stop();
            }
    }

    private void startRecord() {
        //检查sdcard
        if (!BaseUtil.isExitsSdcard()) {
            String needSd = context.getResources().getString(R.string.Send_voice_need_sdcard_support);
            ToastUtils.showToast(context,needSd);
            return ;
        }
        recorder.StartRecording();//开始录制
        countdown = 0;
        cdt.start();
    }

    private void stopRecord() {
        close();
    }
    private void close() {
        dismiss();
        numTime.setText("···00:00···");
        if (recorder != null) {//停止文件写入
            System.out.println("stopRecord");
            recorder.StopRecording();
        }
        cdt.cancel();
    }

    CountDownTimer cdt = new CountDownTimer(20000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            countdown ++;
            //将秒转换成分秒
            Date dates = new Date(countdown * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
            String times = sdf.format(dates);
            numTime.setText("···" + times + "···");
        }
        @Override
        public void onFinish() {
            numTime.setText("···00:00···");
            isStart = false;
            if (ivToggle != null){
                ivToggle.setImageResource(R.mipmap.icon_stop);
            }
            stopRecord();
            if (!new File(filePath).exists()) {
                Toast.makeText(context, "录音失败", Toast.LENGTH_SHORT).show();
            } else {
                if (mCallback!=null){
                    mCallback.getData(filePath,countdown);
                }

            }
        }
    };

    /**
     * 定义一个接口
     */
    public interface AudioCallback {
        void getData(String filePath,int countdown);
    }
    /**
     * 设置按钮的事件
     * @param callback 监听
     * @return
     */
    public void getAudioBack(AudioCallback callback) {
        mCallback = callback;
    }
}
